from typing import Optional

from django.shortcuts import render

# Create your views here.
from drf_yasg.utils import swagger_auto_schema
from rest_framework import viewsets
from rest_framework.decorators import api_view

from common.paginatedViewMixin import PaginatedViewMixin
from common.standard_pagination import StandardPagination
from utils import response_body_utils
from utils.mqtt_utils import MqttClient
from utils.response_body_utils import get_success_response, get_error_response
from .models import *
from system.serializers import *


class EnvInfoView(viewsets.GenericViewSet, PaginatedViewMixin):
    queryset = EnvInfo.objects.all().filter(is_deleted=0).order_by("-update_time")
    serializer_class = EnvInfoModelSerializer
    pagination_class = StandardPagination  # 使用自定义的分页类

    def add(self, request):
        name = request.data["name"]
        if self.get_queryset().filter(name=name).first():
            return get_error_response(response_body_utils.DATA_DUPLICATION)
        # 反序列化
        serializer = EnvInfoModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return get_success_response("")
        return get_success_response("")

    def update(self, request):
        req_data = request.data
        if self.get_queryset().filter(id=req_data["id"]).first():
            self.get_queryset().filter(id=req_data["id"]).update(**req_data)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.DATA_ABSENT)

    def list(self, request):
        get_queryset = self.get_queryset()
        if request.GET.get("project_id"):
            get_queryset = get_queryset.filter(project_id=request.GET.get("project_id"))
        data = self.get_serializer(get_queryset, many=True).data
        return get_success_response(data)

    def page(self, request):
        get_queryset = self.get_queryset()
        if request.GET.get("project_id"):
            get_queryset = get_queryset.filter(project_id=request.GET.get("project_id"))
        return super().base_page(request, get_queryset)

    def delete(self, request, **kwargs):

        if kwargs.get("pk"):
            EnvInfo.objects.all().filter(id=kwargs["pk"]).update(is_deleted=1)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.PARAMS_MISSING)


class EnvParamsView(viewsets.GenericViewSet, PaginatedViewMixin):
    queryset = EnvParams.objects.all().filter(is_deleted=0).order_by("-update_time")
    serializer_class = EnvParamsModelSerializer
    pagination_class = StandardPagination  # 使用自定义的分页类

    def add(self, request):
        name = request.data["name"]
        if self.get_queryset().filter(name=name, project_id=request.data["project_id"]).first():
            return get_error_response(response_body_utils.DATA_DUPLICATION)
        # 反序列化
        serializer = EnvParamsModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return get_success_response("")
        return get_success_response("")

    def update(self, request):
        req_data = request.data
        if self.get_queryset().filter(id=req_data["id"]).first():
            env_params = EnvParams.objects.get(id=req_data["id"])
            serializer = EnvParamsModelSerializer(env_params, data=req_data, partial=True)
            if serializer.is_valid():
                serializer.save()
            else:
                return get_error_response(response_body_utils.PARAMS_MISSING)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.DATA_ABSENT)

    def list(self, request):
        env_params = self.get_queryset()
        if request.GET.get("project_id"):
            env_params = self.get_queryset().filter(project_id=request.GET.get("project_id"))
        data = list(env_params.values())
        return get_success_response(data)

    def page(self, request):
        get_queryset = self.get_queryset()
        if request.GET.get("project_id"):
            get_queryset = get_queryset.filter(project_id=request.GET.get("project_id"))
        return super().base_page(request, get_queryset)

    def delete(self, request, **kwargs):

        if kwargs.get("pk") and self.get_queryset().filter(id=kwargs["pk"]).first():
            self.get_queryset().filter(id=kwargs["pk"]).update(is_deleted=1)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.PARAMS_MISSING)


class DBConnectionView(viewsets.GenericViewSet, PaginatedViewMixin):
    queryset = DBConnection.objects.all().filter(is_deleted=0).order_by("-update_time")
    serializer_class = DBConnectionModelSerializer
    pagination_class = StandardPagination  # 使用自定义的分页类

    def add(self, request):
        name = request.data["name"]
        if self.get_queryset().filter(name=name, project_id=request.data["project_id"]).first():
            return get_error_response(response_body_utils.DATA_DUPLICATION)
        # 反序列化
        serializer = DBConnectionModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return get_success_response("")
        else:
            print(serializer.errors)
            return get_error_response(response_body_utils.PARAMS_MISSING)

    def update(self, request):
        req_data = request.data
        if self.get_queryset().filter(id=req_data["id"]).first():
            self.get_queryset().filter(id=req_data["id"]).update(**req_data)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.DATA_ABSENT)

    def delete(self, request, **kwargs):

        if kwargs.get("pk"):
            DBConnection.objects.all().filter(id=kwargs["pk"]).update(is_deleted=1)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.PARAMS_MISSING)

    def list(self, request):
        get_queryset = self.get_queryset()
        if request.GET.get("project_id"):
            get_queryset = self.get_queryset().filter(project_id=request.GET.get("project_id"))
        serializer = DBConnectionModelSerializer(get_queryset, many=True).data
        return get_success_response(serializer)

    def page(self, request):
        get_queryset = self.get_queryset()
        return super().base_page(request, get_queryset)


class MqttconnectionView(viewsets.GenericViewSet):
    mqtt_client_instance: Optional[MqttClient] = None

    def connect_mqtt(self, request):
        global mqtt_client_instance
        if not mqtt_client_instance:
            mqtt_client_instance = MqttClient(broker='your_broker_address', port=1883, client_id='unique_client_id')
            mqtt_client_instance.connect()
        return get_success_response("connect")

    def publish_message(self, request):
        global mqtt_client_instance
        if mqtt_client_instance:
            topic = request.GET.get('topic', '')
            message = request.GET.get('message', '')
            result = mqtt_client_instance.publish(topic, message)
            return get_success_response(result)
        return get_error_response(response_body_utils.MQTT_DISCONNECT)

    def disconnect_mqtt(self, request):
        global mqtt_client_instance
        if mqtt_client_instance:
            mqtt_client_instance.disconnect()
            mqtt_client_instance = None
            return get_success_response("disconnect")
        return get_error_response(response_body_utils.MQTT_DISCONNECT)
